
package com.thor.palmmall.hdmall.media.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.activation.DataHandler;

import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StreamUtils;

import com.thor.commons.exception.ThorServiceException;
import com.thor.commons.util.Assert;
import com.thor.palmmall.hdmall.common.HDMBaseServiceImpl;
import com.thor.palmmall.hdmall.media.HDMFileUploadResponse;
import com.thor.palmmall.hdmall.media.HDMMediaService;

public class HDMediaServiceImpl extends HDMBaseServiceImpl implements HDMMediaService {

  @Override
  public List<String> upload(Attachment attachment) throws ThorServiceException {

    MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();

    final DataHandler dataHandler = attachment.getDataHandler();
    try {
      ByteArrayResource arrayResource = new ByteArrayResource(
          StreamUtils.copyToByteArray(attachment.getObject(InputStream.class))) {
        @Override
        public String getFilename() throws IllegalStateException {
          return dataHandler.getName();
        }
      };
      map.add("file", arrayResource);
      HDMFileUploadResponse resp = upload("/api/file/upload", map, HDMFileUploadResponse.class);
      if (resp != null) {
        return resp.getData();
      }

    } catch (IOException e) {
      throw new ThorServiceException("上传文件失败");
    }

    return null;
  }

  @Override
  public byte[] download(String moduleName, String num, String fileName)
      throws ThorServiceException {

    Assert.assertArgumentNotNull(moduleName, "moduleName");
    Assert.assertArgumentNotNull(num, "num");
    Assert.assertArgumentNotNull(fileName, "fileName");

    byte[] byteArr = download("/api/file/{moduleName}/{num}/{fileName}", byte[].class, moduleName,
        num, fileName);
    return byteArr;
  }

}
